package com.asdc.autoscanfiles.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class DateUtils {
	/**
	 * yyyyMMdd
	 */
	private static final String DATE_NO_SPACE_FORMAT_STR = "yyyyMMdd";
	/**
	 * yyyyMM
	 */
	private static final String YEARMONTH_NO_SPACE_FORMAT_STR = "yyyyMM";
	/**
	 * yyyy-MM-dd HH:mm:ss
	 */
	private static final String DATE_TIME_SECOND_FORMAT_STR = "yyyy-MM-dd HH:mm:ss";
	private static final DateTimeFormatter DATE_NO_SPACE_FORMAT_STR_FORMTTER = DateTimeFormat
			.forPattern(DATE_NO_SPACE_FORMAT_STR);

	/**
	 * parse date with formatter: yyyyMMdd
	 * 
	 * @return
	 */
	public static Date parseNoSpaceDate(String str) {
		if(str.length()!=8) {
			return null;
		}
		if("00".equals(str.substring(6,8))) {
			str = str.substring(0,6)+"01";
		}
		DateTime dt = DateTime.parse(str, DATE_NO_SPACE_FORMAT_STR_FORMTTER);
		return dt.toDate();
	}

	public static String getYearMonthNoSpaceStr(Date date) {
		return new DateTime(date.getTime()).toString(YEARMONTH_NO_SPACE_FORMAT_STR);
	}

	public static Date getNextMonthFirstDay(Date date) {
		DateTime dt = new DateTime(date.getTime());
		dt = dt.withDayOfMonth(1);
		dt = dt.plusMonths(1);
		return dt.toDate();
	}

	public static String getDateStr(Date date) {
		return new DateTime(date.getTime()).toString(DATE_TIME_SECOND_FORMAT_STR);
	}

	public static void main(String[] args) {
		System.out.println("19770101".substring(0,6)+"01");
	}

	/**
	 * 获取所输入日期该月的第一天和最后一天
	 * @param dateStr 输入日期
	 * @param inputDateFormat 输入日期的格式 例：yyyy-MM
	 * @param outputDateFormat 期望输出的日期格式 例：yyyy-MM-dd
	 * @return 返回key为"firstDay"、"lastDay"的map
	 * @throws ParseException
	 */
	public static Map<String, String> getFirstDayAndLastDayOfMonth(String dateStr, String inputDateFormat, String outputDateFormat) throws ParseException {
		Map<String, String> resultMap = new HashMap();

		Calendar firstCalendar = Calendar.getInstance();
		Calendar lastCalendar = Calendar.getInstance();

		SimpleDateFormat inputFormat = new SimpleDateFormat(inputDateFormat);
		SimpleDateFormat outputFormat = new SimpleDateFormat(outputDateFormat);
		Date inputDate = inputFormat.parse(dateStr);

		firstCalendar.setTime(inputDate);
		lastCalendar.setTime(inputDate);
		firstCalendar.set(Calendar.DAY_OF_MONTH, 1);// 设置该月的第一天

		lastCalendar.add(Calendar.MONTH, 1);// 加一个月
		lastCalendar.set(Calendar.DATE, 1);// 设置为该月第一天
		lastCalendar.add(Calendar.DATE, -1);// 再减一天即为上个月最后一天

		resultMap.put("firstDay", outputFormat.format(firstCalendar.getTime()));
		resultMap.put("lastDay", outputFormat.format(lastCalendar.getTime()));
		return resultMap;
	}
}
